package com.example.service.impl;

import com.example.common.Result;
import com.example.common.PageResult;
import com.example.dto.StockRecordQueryDTO;
import com.example.mapper.StockRecordMapper;
import com.example.service.AdminStockService;
import com.example.vo.StockRecordVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员库存管理服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminStockServiceImpl implements AdminStockService {

    private final StockRecordMapper stockRecordMapper;

    @Override
    public Result<PageResult<StockRecordVO>> getStockRecordsPage(StockRecordQueryDTO queryDTO) {
        try {
            // 管理员只查看管理员相关的库存记录
            // 过滤条件：操作员名称不包含"(店长入库)"和"(店长出库)"
            PageHelper.startPage(queryDTO.getPage(), queryDTO.getSize());
            List<StockRecordVO> records = stockRecordMapper.selectAdminStockRecords(queryDTO);
            
            // 设置记录类型显示名称
            records.forEach(record -> {
                if ("IN".equals(record.getRecordType())) {
                    record.setRecordTypeName("入库");
                } else if ("OUT".equals(record.getRecordType())) {
                    record.setRecordTypeName("出库");
                }
            });
            
            PageInfo<StockRecordVO> pageInfo = new PageInfo<>(records);
            PageResult<StockRecordVO> pageResult = new PageResult<>(
                    pageInfo.getPageNum(),
                    pageInfo.getPageSize(),
                    pageInfo.getTotal(),
                    pageInfo.getList()
            );
            
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询库存记录失败", e);
            return Result.error("查询库存记录失败：" + e.getMessage());
        }
    }

    @Override
    public Result<PageResult<StockRecordVO>> getInRecordsPage(int page, int size, String productName, 
                                                              String productCode, String startTime, String endTime) {
        try {
            StockRecordQueryDTO queryDTO = new StockRecordQueryDTO();
            queryDTO.setPage(page);
            queryDTO.setSize(size);
            queryDTO.setProductName(productName);
            queryDTO.setProductCode(productCode);
            queryDTO.setRecordType("IN"); // 只查询入库记录
            queryDTO.setStartTime(startTime);
            queryDTO.setEndTime(endTime);
            
            PageHelper.startPage(page, size);
            List<StockRecordVO> records = stockRecordMapper.selectAdminStockRecords(queryDTO);
            
            // 设置记录类型显示名称
            records.forEach(record -> record.setRecordTypeName("入库"));
            
            PageInfo<StockRecordVO> pageInfo = new PageInfo<>(records);
            PageResult<StockRecordVO> pageResult = new PageResult<>(
                    pageInfo.getPageNum(),
                    pageInfo.getPageSize(),
                    pageInfo.getTotal(),
                    pageInfo.getList()
            );
            
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询入库记录失败", e);
            return Result.error("查询入库记录失败：" + e.getMessage());
        }
    }

    @Override
    public Result<PageResult<StockRecordVO>> getOutRecordsPage(int page, int size, String productName, 
                                                               String productCode, String operatorName, 
                                                               String startTime, String endTime) {
        try {
            StockRecordQueryDTO queryDTO = new StockRecordQueryDTO();
            queryDTO.setPage(page);
            queryDTO.setSize(size);
            queryDTO.setProductName(productName);
            queryDTO.setProductCode(productCode);
            queryDTO.setOperatorName(operatorName);
            queryDTO.setRecordType("OUT"); // 只查询出库记录
            queryDTO.setStartTime(startTime);
            queryDTO.setEndTime(endTime);
            
            PageHelper.startPage(page, size);
            List<StockRecordVO> records = stockRecordMapper.selectAdminStockRecords(queryDTO);
            
            // 设置记录类型显示名称
            records.forEach(record -> record.setRecordTypeName("出库"));
            
            PageInfo<StockRecordVO> pageInfo = new PageInfo<>(records);
            PageResult<StockRecordVO> pageResult = new PageResult<>(
                    pageInfo.getPageNum(),
                    pageInfo.getPageSize(),
                    pageInfo.getTotal(),
                    pageInfo.getList()
            );
            
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询出库记录失败", e);
            return Result.error("查询出库记录失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<StockRecordVO>> getStockRecordsByProductId(Long productId) {
        try {
            // 构造查询条件，只查询管理员相关的记录
            StockRecordQueryDTO queryDTO = new StockRecordQueryDTO();
            // 这里需要根据productId查询，但selectAdminStockRecords不支持productId参数
            // 暂时使用原方法，后续可以扩展
            List<StockRecordVO> records = stockRecordMapper.selectByProductId(productId);
            
            // 过滤掉店长的记录
            records = records.stream()
                    .filter(record -> !record.getOperatorName().contains("(店长入库)") 
                                   && !record.getOperatorName().contains("(店长出库)"))
                    .collect(java.util.stream.Collectors.toList());
            
            // 设置记录类型显示名称
            records.forEach(record -> {
                if ("IN".equals(record.getRecordType())) {
                    record.setRecordTypeName("入库");
                } else if ("OUT".equals(record.getRecordType())) {
                    record.setRecordTypeName("出库");
                }
            });
            
            return Result.success(records);
        } catch (Exception e) {
            log.error("根据商品ID查询库存记录失败，商品ID: {}", productId, e);
            return Result.error("查询库存记录失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<StockRecordVO>> exportStockRecords(StockRecordQueryDTO queryDTO) {
        try {
            List<StockRecordVO> records = stockRecordMapper.selectAdminStockRecords(queryDTO);
            
            // 设置记录类型显示名称
            records.forEach(record -> {
                if ("IN".equals(record.getRecordType())) {
                    record.setRecordTypeName("入库");
                } else if ("OUT".equals(record.getRecordType())) {
                    record.setRecordTypeName("出库");
                }
            });
            
            return Result.success(records);
        } catch (Exception e) {
            log.error("导出库存记录失败", e);
            return Result.error("导出库存记录失败：" + e.getMessage());
        }
    }

    @Override
    public Result<Object> getStockStatistics(String startTime, String endTime) {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 查询入库统计
            StockRecordQueryDTO inQuery = new StockRecordQueryDTO();
            inQuery.setRecordType("IN");
            inQuery.setStartTime(startTime);
            inQuery.setEndTime(endTime);
            
            List<StockRecordVO> inRecords = stockRecordMapper.selectAdminStockRecords(inQuery);
            int totalInQuantity = inRecords.stream().mapToInt(StockRecordVO::getQuantity).sum();
            BigDecimal totalInCost = inRecords.stream()
                    .filter(record -> record.getTotalCost() != null)
                    .map(StockRecordVO::getTotalCost)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            // 查询管理员出库统计
            StockRecordQueryDTO outQuery = new StockRecordQueryDTO();
            outQuery.setRecordType("OUT");
            outQuery.setStartTime(startTime);
            outQuery.setEndTime(endTime);
            
            List<StockRecordVO> outRecords = stockRecordMapper.selectAdminStockRecords(outQuery);
            int totalOutQuantity = outRecords.stream().mapToInt(StockRecordVO::getQuantity).sum();
            BigDecimal totalOutCost = outRecords.stream()
                    .filter(record -> record.getTotalCost() != null)
                    .map(StockRecordVO::getTotalCost)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            statistics.put("totalInRecords", inRecords.size());
            statistics.put("totalOutRecords", outRecords.size());
            statistics.put("totalInQuantity", totalInQuantity);
            statistics.put("totalOutQuantity", totalOutQuantity);
            statistics.put("totalInCost", totalInCost);
            statistics.put("totalOutCost", totalOutCost);
            statistics.put("netQuantity", totalInQuantity - totalOutQuantity);
            statistics.put("netCost", totalInCost.subtract(totalOutCost));
            
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取库存统计信息失败", e);
            return Result.error("获取库存统计信息失败：" + e.getMessage());
        }
    }
} 